package top.hudk.design.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * 功能或业务描述：代理类逻辑
 * 创建时间：2021/5/14 20:08
 * 作者：hudk
 */
public class ProxyHandler implements InvocationHandler {

    /**
     * 被代理的类
     */
    private Object object;

    public ProxyHandler(Object object){
        this.object = object;
    }

    /**
     * 回调方法，包含代理逻辑
     * 可应用模板方法模式增加扩展性
     * @param proxy
     * @param method
     * @param args
     * @return
     * @throws Throwable
     */
    @Override
    public final Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        beforeHandle(proxy,method,args);
        Object invokeResult = method.invoke(object, args);
        afterHandle(proxy, method, args);
        return invokeResult;
    }

    /**
     * 前置处理逻辑
     * @param proxy
     * @param method
     * @param args
     */
    private void beforeHandle(Object proxy, Method method, Object[] args){
        System.out.println("Before invoke "  + method.getName());
    }

    /**
     * 后置处理逻辑
     * @param proxy
     * @param method
     * @param args
     */
    private void afterHandle(Object proxy, Method method, Object[] args){
        System.out.println("After invoke " + method.getName());
    }
}
